<template>
	<view class="page">
		<!-- table组件 -->
		<th-table :columns="tableOptions.tableColumns" :dataList="tableOptions.tableData" ref="multipleTable" :loading="saveLoading">
			<!-- 新增删除 -->
			<template v-slot:operate="{scope}">
				<view class="process-box" v-if="visibleDateTime(scope)">
					<wd-button type="icon" icon="add-circle" danger style="color:#4d80f0;" @click="addRow(scope)">
					</wd-button>
					<wd-button type="icon" icon="delete" danger style="color:#fa4350;" @click="removeRow(scope)">
					</wd-button>
				</view>
			</template>
			<!-- 序号 -->
			<template v-slot:index="{scope}">
				{{gxRank.indexOf(scope.row.id) + 1}}
			</template>
			<!-- 操作时间 -->
			<template v-slot:operateTime="{scope}">
				<th-datetime-picker
				  v-if="visibleDateTime(scope)"
				  :limit="returnLimit(scope)"
				  v-model:value="scope.row.operateTime"
				  format="YYYY-MM-DD HH:mm:ss"
				  placeholder="请选择日期"
				  @change="operateTimeChange($event,scope)"
				></th-datetime-picker>
			</template>
			<!-- 物料名称 -->
			<template v-slot:invName="{scope}">
		     <th-select
			      v-if="visibleSelect(scope)"
		          :options="processMaterialDTOS(scope)"
		          v-model:value="scope.row.dosageId"
				  @change="onSelectMaterial($event,scope)"
		        ></th-select>  		
			</template>
			<!-- 实测值 -->
			<template v-slot:schemeParamValue="{scope}">
				{{showDetail(scope,'schemeParamValue')}}
			</template>
			<!-- 工序累计 -->
			<template v-slot:sum="{scope}">
				{{showDetail(scope,'sum')}}
			</template>
			<!-- 总累计 -->
			<template v-slot:total="{scope}">
				{{showDetail(scope,'total')}}
			</template>

			<!-- 实测值 -->
			<template v-slot:paramValue="{scope}">
				<!-- @input="paramValueChange($event,scope)" -->
				 <input v-if="visibleInput(scope)" type="number" placeholder="请输入" placeholder-style="color:#bfbfbf;font-size:28rpx;" :value="showDetail(scope,'paramValue')"  @blur="blurHandle($event,scope)">
			</template>
		</th-table>
	</view>
</template>

<script lang="ts" setup>
import thTable from './th-table.vue'
import thSelect from '@/pages/pm/assay-report/component/th-select.vue'
import thDatetimePicker from '@/pages/pm/assay-report/component/th-datetime-picker.vue'
import showModal from '@/utils/modal';

import { request } from '@/utils/request'
import { formatByDayjs } from '@/utils/util';

const props = defineProps({
	recordId:{
		type:String
	},
    stepList: {
		type:Array,
		default:()=>{
			return []
		}
	},
	materialList:{
		type:Array,
		default:()=>{
			return []
		}
	}
})


const returnLimit = (scope:any)=>{
	const { row } = scope;
	const processFilterMap = dataList.value.filter(item => row.processName == item.processName && row.sn == item.sn)
	// 第一行不限制
	if(processFilterMap[0].rowIndex === row.rowIndex ){
		return null
	}
	//只有一行不限制
	if(processFilterMap.length === 1){
		return null
	}
	const startTime =  processFilterMap[0].operateTime
	
	if(!startTime){
		return {
			value:null,
			tip:'先选择开始日期'
		}
	}else{
		return {
			value:startTime,
			tip:'选择日期不能小于开始日期'
		}
	}
}

/**
 * 查找工序
 */


const findProcessName = (payload):any => {
    return props.stepList.find(item => item.processName == payload.row.processName && payload.row.sn == item.sn)
}

/**
 * 当前工序下的物料数组
 */
const processMaterialDTOS = ({ row }) => {
    const process = props.stepList.find(item => item.processName == row.processName && row.sn == item.sn)
    return process ? process.dosageList.map(dos=>{
		return {
			label:dos.invName,
			value:dos.id
		}
	}) : []
}

/**
 * 时间框是否需要加载
 * @param payload 
 */
const visibleDateTime = (payload) => {
    const processNameObj:any = findProcessName(payload);

    if (processNameObj) {
        if (!processNameObj.paramList) return false
        return processNameObj.putIntoFlag || processNameObj.paramList?.length
    }

    return false
}

/**
 * 选择框是否需要加载
 */
const visibleSelect = (payload) => {
  const processNameObj: any = findProcessName(payload);

  if (processNameObj) {
    return processNameObj.putIntoFlag;
  }

  return false;
}

/**
 * 输入框是否需要加载
 * 
 */
const visibleInput = (payload) => {
    const processNameObj: any = findProcessName(payload)
    if (processNameObj) {
        if (!processNameObj.paramList) return false
        return processNameObj.paramList?.some(item => {
            const columnKey = `${item.paramName}(${item.paramUnit})`
            return columnKey == payload.column.parentProp
        })
    }

    return false
}

/**
 * 校验物料在不在工序下
 */
const isMaterialInProcess = (item) => {
    return visibleDateTime({ row: item })
}

/**
 * 根据当前行查找对应的工序下的所有行
 */
const findProcess = (row) => {
    return dataList.value.filter(item => item.processName == row.processName && row.sn == item.sn)
}

// 校验行编辑
const validateRow = (row) => {
    let rowRrrs = [];
    // 判断有没有物料和参数
    if (isMaterialInProcess(row)) {
        //操作时间 || ( 有物料 && 没选 )
        if (!row.operateTime || (visibleSelect({ row }) && !row.invName) || row.paramColumns.every(item => ['',null].includes(item.paramValue))) {
            rowRrrs.push({row})
        }
    }
    if (!rowRrrs.length) {
        autoSaveRow(row)
    }

}

/**
 * 工序去重
 */
const filterProcess = (row) => {
    const processList = findProcess(row)
    const filterProcess = onActionProcessList.value.find(item => item => item.processName == row.processName && row.sn == item.sn)
    if (!filterProcess) {
        onActionProcessList.value.push(...processList)
    }

}
const saveLoading = ref(false)
// 自动保存行
const autoSaveRow = async (row) => {
    filterProcess(row)
    const param = [...onActionProcessList.value, ...removeList.value]
    param.forEach(item => {
        item.paramColumns.forEach(p => {
            if (p.paramValue == "") p.paramValue = p.id?'': null
            if (p.schemeParamValue == "") p.schemeParamValue = null
        })
    })
    
    saveLoading.value = true
    try {
        await request({
            url: `/pm/experimentRecord/stepTable`,
            method: 'POST',
            data: param
        });
        getStepTable();
        onActionProcessList.value = []
        removeList.value = []
		uni.$emit('updateStep',props.recordId)
    } catch (error) {
        console.log(error);
    }

    saveLoading.value = false
}



const getStepTable = ()=>{
  request({
	url: `/pm/experimentRecord/stepTable/${props.recordId}`,
	method: 'GET'
  }).then((res:any)=>{
	dataList.value = res.data.filter(item => !['中控', '终检'].includes(item['processName']) && ![4].includes(item.status)).map((item,index)=>{
		item.rowIndex = index;
		return item;
	})
	paramsColumn.value = res.data[0].paramColumns;
	dataList.value.forEach(item=>{
		if(!gxRank.value.includes(item.id)){
			gxRank.value.push(item.id)
		}
	})	
})
}

const showDetail = (scope,key)=>{
	const {row,column} = scope;
	const findTd = row.paramColumns.find((item)=>{
		return item.columnKey == column.parentProp;
	})
	return findTd[key];
}

// const paramValueChange = (e,scope)=>{
// 	const {row,column} = scope;
// 	const findTd = row.paramColumns.find((item)=>{
// 		return item.columnKey == column.parentProp;
// 	})
// 	findTd.paramValue = e.detail.value
// }

const blurHandle = (e,scope:any)=>{
	const {row,column} = scope;
	const findTd = row.paramColumns.find((item)=>{
		return item.columnKey == column.parentProp;
	})
	
	// input值改变了
	if(e.detail.value !== findTd.paramValue){
		findTd.paramValue = e.detail.value;
		validateRow(row)
	}
}

// 时间更改
const operateTimeChange = (e,scope:any)=>{
	setTimeout(()=>{
		validateRow(scope.row)
	},300)
}

const onSelectMaterial = function (e,scope) {
	const {row} = scope;
	if(!e){
		row.invName = null;
		row.unit =  null;
		row.invStd =  null;
		row.dosage =  null;
		return;
	}
	const process:any = props.stepList.find((item:any) => item.processName == row.processName && row.sn == item.sn)
    const currentMaterial: any = process.dosageList.find((item:any) => item.id === e.value);
    if (currentMaterial) {
        row.invName = currentMaterial.invName || ""
        row.unit = currentMaterial.unit || null;
        row.invStd = currentMaterial.invStd || '';
        row.dosage = currentMaterial.initDosage || null,
		setTimeout(() => {
			  validateRow(row)
		  }, 300)
		
    };
}

/**
 * 表格全量校验
 */
const validate = () => {
    const validateErrs = []
    const arr = tableOptions.value.tableData.filter(item => item.status != 4)
    arr.map((item, index) => {
        // 判断有没有物料和参数
        if (isMaterialInProcess(item)) {
            //操作时间 || ( 有物料 && 没选 )
            if (!item.operateTime || (visibleSelect({ row: item }) && !item.invName) || item.paramColumns.every(v =>['',null].includes(v.paramValue))) {
                validateErrs.push({
                    item,
                    rowIndex: index
                })
            }

        }
    })
    if (validateErrs.length) {
		const row = validateErrs[0].item;
		if(!row.operateTime){
			 uni.showToast({
				title:`请填写${row.processName}工序操作时间`,
				icon:'none'
			 })
			 return true;
		} else if(visibleSelect({ row }) && !row.invName) {
			uni.showToast({
				title:`请选择${row.processName}工序物料`,
				icon:'none'
			})
			return true;
		}else{
			uni.showToast({
				title:`${row.processName}工序至少一个实测值不为空`,
				icon:'none'
			})
			return true;
		}
    }
	
    return validateErrs.length ? true : false
}

const columns = ref([{
  label: "",
  prop:'operate',
  align: "center",
  render:'operate',
  width:60,
  fixed:'left',
},
{
  label: "序号",
  prop:'index',
  align: "center",
  render:'index',
  fixed:'left',
  width:60,
  customCell: (record:any) => {
	return settleCol(record.id, record.rowIndex);
  }
},
{
  label: "工序",
  prop:'processName',
  width:60,
  align: "center",
  fixed:'left',
  customCell: (record:any) => {
	return settleCol(record.id, record.rowIndex);
  },
},
{
  label: "操作时间",
  prop:'operateTime',
  align:'center',
  render:'operateTime',
  width:200
},
{
  label: "物料名称",
  prop:'invName',
  align:'center',
  width:160,
  render:'invName'
}])
  
const dataList = ref([])
const paramsColumn = ref([])
const gxRank = ref([])

onMounted(()=>{
	getStepTable();
})




const tableOptions = computed(() => {
    const list = JSON.parse(JSON.stringify(dataList.value));
    if (!list || !list.length) return {
        tableColumns: [],
        tableData: []
    };

    const fixList = []
    const t = paramsColumn.value.filter(item => item.paramName.includes('投料量'))
    if (t) {
        fixList.push(...t)
    }
    const j = paramsColumn.value.filter(item => item.paramName.includes('进料速度'))
    if (j) {
        fixList.push(...j)
    }
    const otherArr = paramsColumn.value.filter(i => !fixList.find(p => p.paramName == i.paramName))

    const arr = fixList.concat(otherArr)
    const temp:any[] = arr.map(item => {
        let defaultObj = {
            label: item.columnKey,
            align: 'center',
            children: [{
                label: '目标值',
                prop: 'schemeParamValue',
                parentProp: item.columnKey,
                align: 'center',
                width: 80,
				render:'schemeParamValue'
            },
            {
                label: '实测值',
                prop: 'paramValue',
                align: 'center',
                parentProp: item.columnKey,
                width: 80,
				render:'paramValue'
            }]
        }

        if (item.paramName == '投料量') {
            return {
                label: item.columnKey,
                align: 'center',
                children: [
                    {
                        label: '实测值',
                        prop: 'paramValue',
                        parentProp: item.columnKey,
                        align: 'center',
                        width: 80,
						render:'paramValue'
                    },
                    {
                        label: '工序累计值',
                        prop: 'sum',
                        parentProp: item.columnKey,
                        align: 'center',
                        width: 90,
						render:'sum'
                    },
                    {
                        label: '总累计值',
                        prop: 'total',
                        align: 'center',
                        parentProp: item.columnKey,
                        width: 80,
						render:'total'
                    },]
            }
        }
        return defaultObj
    })
    const l = columns.value.concat(temp)
    return {
        tableColumns: l,
        tableData: dataList.value
    }
})

const refer = computed(()=>{
	const refer = {}
	tableOptions.value.tableData.forEach((row) => {
	  const k = row.id;
	  if (refer[k]) {
	    refer[k].push({ rowIndex: row.rowIndex });
	  } else {
	    refer[k] = [{ rowIndex: row.rowIndex }];
	  }
	});
	Object.keys(refer).forEach((key) => {
	  refer[key].forEach((item:any, index:number) => {
	    if (index === 0) {
	      item.col = refer[key].length;
	    } else {
	      item.col = 0;
	    }
	  });
	});
	return refer;
})

const settleCol = (key:string, rowIndex:number)=>{
  const match = refer.value[key].find((item:any) => {
	return item.rowIndex === rowIndex;
  });
  return { rowSpan: match.col };
}

let canAdd = true;
const addRow = (scope:any)=>{
	if(!canAdd) return;
	const row = JSON.parse(JSON.stringify(scope.row))
	
    const processFilterMap = dataList.value.filter(item => row.processName == item.processName && row.sn == item.sn)
	const startTime = processFilterMap[0].operateTime;
    // 新增行时如果第一行没有开始时间不能新增
    if(!startTime){
    	uni.showToast({
    		title:'请先填写开始时间再新增',
    		icon:'none'
    	})
		return;
    }
	canAdd = false
	row.paramColumns.forEach(item => {
		  item.id = null
		  item.paramValue = null
	})
	dataList.value.splice(scope.$index + 1,0,{
		 ...row,
		add:true,
		rowIndex:new Date().getTime(),
		invName: null,
		dosageId:null,
		operateTime:formatByDayjs(new Date(), 'YYYY-MM-DD HH:mm:ss'),
	})
	
	setTimeout(()=>{
		canAdd = true;
	},1000)
}


/**
 * 删除行
 */

const removeList = ref([]);
const onActionProcessList = ref([]);
const onRemoveRow = (payload) => {
    filterProcess(payload.row)
    removeList.value.push(payload.row)
}

const removeRow = (scope:any)=>{
	showModal({
	  title: '提示',
	  content: '确定要删除数据吗？',
	  showCancel: true,
	  confirm: () => {
	    const match = dataList.value.filter(item=> item.id === scope.row.id);
	    if(match?.length>1){
			if(!scope.row.add){
				scope.row.status = 4;
				onRemoveRow(scope)
			}
			
			dataList.value.splice(scope.$index,1)
	    }else{
	    	uni.showToast({
	    		title:'当前工序必须保留一行数据',
	    		icon:'none'
	    	})
	    }
	  },
	});
}


const saveHandle = async (type:string)=>{
	if(saveLoading.value) return;
	if (type == 'save' && validate()) return;
	saveLoading.value = true;
	  const param = [...dataList.value, ...removeList.value]
	  try {
	    await request({
	      url: `/pm/experimentRecord/stepTable`,
	      method: 'POST',
	      data: param
	    });
	    if (type == 'save') {
	      getStepTable();
	    } 
		uni.$emit('updateStep',props.recordId);
	 }catch(err){
		 console.log(err)
	 }
	 saveLoading.value = false;
}

defineExpose({
    saveHandle
})

</script>

<style lang="scss">
.page{
	.block{
		margin-bottom:30rpx;
		.title{
			padding:15rpx 0;
		}
	}
	.input{
		margin:10rpx;
	}
}
.process-box{
	display: flex;
	justify-content: center;
	align-items: center;
	.add-icon{
		width:30rpx;
		height:30rpx;
		text-align:center;
		line-height:29rpx;
		border:1px solid #2e5cf6;
		color:#2e5cf6;
		font-weight:bold;
		border-radius:50%;
	}
	.delete-icon{
		width:30rpx;
		height:30rpx;
		text-align:center;
		line-height:29rpx;
		border:1px solid #ff4d4f;
		color:#ff4d4f;
		font-weight:bold;
		border-radius:50%;
		margin-left:20rpx;
	}
}
</style>